#!/usr/bin/env bash

# pid file
PID_FILE_NAME="pid_file"

# file to upload
EXECUTABLE_JAR_NAME="visualnovel.jar"
TMP_EXECUTABLE_JAR_NAME=${EXECUTABLE_JAR_NAME}".tmp"
EXECUTABLE_JAR_PATH="./target/${EXECUTABLE_JAR_NAME}"

DEPLOY_SCRIPT="deploy.sh"
START_FUNC_NAME="start"

# ssh remote
ENV_TEST="test"
SSH_HOST_TEST="root@52.3.63.25"
WORK_DIR_TEST="/data/console/backend/"
PORT_TEST="22"

ENV_PRODUCTION="online"
SSH_HOST_PRODUCTION="root@47.253.186.9"
WORK_DIR_PRODUCTION="/data/console/backend/"
PORT_PRODUCTION="22"

# log file
declare LOG_FILES
NOHUP_LOG="nohup.out"
LOG_BACKUP_FOLDER="logs/"

# generator tables
function generate() {
    cd generator
    java -classpath jooq-3.9.1.jar:jooq-meta-3.9.1.jar:jooq-codegen-3.9.1.jar:mysql-connector-java-5.1.41.jar:. org.jooq.util.GenerationTool mysql.xml
}

function cdToWorkDir() {
    work_dir=`dirname $0`
    cd ${work_dir}
}

# backup logs
function backupLog() {
    if [ ! -d "${LOG_BACKUP_FOLDER}" ]; then
        mkdir ${LOG_BACKUP_FOLDER}
    fi

    if [ -f "${NOHUP_LOG}" ]; then
        time=`date +%Y%m%d%H%M%S`
        cp ${NOHUP_LOG} ${LOG_BACKUP_FOLDER}${NOHUP_LOG}.${time}.log
    fi
}

# restart
function restart() {
    if [ -f "${PID_FILE_NAME}" ]; then
        pid=$(cat ${PID_FILE_NAME})
        kill -9 ${pid}
    fi

    # backup log
    backupLog

    # run
    source /etc/profile
    nohup java -Duser.timezone=UTC -server -Xmx256m -Xms256m -Xmn128m -XX:+DisableExplicitGC  -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled -XX:+UseFastAccessorMethods -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70 -XX:ParallelGCThreads=6 -XX:ParallelCMSThreads=6 -XX:-OmitStackTraceInFastThrow -jar ${EXECUTABLE_JAR_NAME} > ${NOHUP_LOG} 2>&1 &
    echo $! > ${PID_FILE_NAME}
}

# start
function start() {
    cdToWorkDir

    if [ -f "${PID_FILE_NAME}" ]; then
        pid=$(cat ${PID_FILE_NAME})
        kill -9 ${pid}
    fi

    # backup log
    backupLog

    rm ${EXECUTABLE_JAR_NAME}
    mv ${TMP_EXECUTABLE_JAR_NAME} ${EXECUTABLE_JAR_NAME}

    # run
    source /etc/profile
    nohup java -Duser.timezone=UTC -server -Xmx256m -Xms256m -Xmn128m -XX:+DisableExplicitGC  -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled -XX:+UseFastAccessorMethods -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70 -XX:ParallelGCThreads=6 -XX:ParallelCMSThreads=6 -XX:-OmitStackTraceInFastThrow -jar ${EXECUTABLE_JAR_NAME} > ${NOHUP_LOG} 2>&1 &
    echo $! > ${PID_FILE_NAME}
}

function upload() {
    scp -P $2 ${EXECUTABLE_JAR_PATH} $1:$3${TMP_EXECUTABLE_JAR_NAME}
    ret=$?
    if [[ ${ret} -ne 0 ]] ; then
        echo 'Failed to scp jar'
        return 1
    fi

    # upload script
    scp -P $2 ${DEPLOY_SCRIPT} $1:$3
    ret=$?
    if [[ ${ret} -ne 0 ]] ; then
        echo 'Failed to scp script'
        return 1
    fi
}

function deploy() {
    # package
    echo "*******Start to package*******"
    ret=$?
    if [[ ${ret} -ne 0 ]] ; then
        echo 'Failed to package'
        exit ${ret}
    fi

    if [ "$1" = "${ENV_TEST}" ]; then
        mvn clean package -Dmaven.test.skip=true -Ptest
        SSH_HOST=${SSH_HOST_TEST}
        WORK_DIR=${WORK_DIR_TEST}
        PORT=${PORT_TEST}
    elif [ "$1" = "${ENV_PRODUCTION}" ]; then
        mvn clean package -Dmaven.test.skip=true -Ponline
        SSH_HOST=${SSH_HOST_PRODUCTION}
        WORK_DIR=${WORK_DIR_PRODUCTION}
        PORT=${PORT_PRODUCTION}
    else
        # TODO: local
        echo "Unknown env: $1"
        exit
    fi

    # upload jar and deploy.sh
    echo "*******Start to upload*******"
    upload ${SSH_HOST} ${PORT} ${WORK_DIR}
    ret=$?
    if [[ ${ret} -ne 0 ]] ; then
        echo 'Failed to upload files'
        exit ${ret}
    fi

    # run
    echo "*******Start to call remote start function*******"
    ssh ${SSH_HOST} -p ${PORT} "bash  ${WORK_DIR}${DEPLOY_SCRIPT} ${START_FUNC_NAME}"
    mvn clean
    echo "*******Done*******"
}

if [ "$1" = "${START_FUNC_NAME}" ]; then
    start
elif [ "$1" = "model" ]; then
    generate
elif [ "$1" = "restart" ]; then
    restart
elif [ "$1" = "${ENV_TEST}" ]; then
    deploy $1
elif [ "$1" = "${ENV_PRODUCTION}" ]; then
    deploy $1
else
    echo "miss argument!"
fi
